import { getFirstMenuPath, filterRouters } from '@/unit/tool';

function aa(obj, pagePath) {
  let { path, children } = obj;
  let list = [];
  if (path == pagePath) {
    list.push(children);
  }
  if (children && children.length > 0) {
    children.forEach((item) => {
      list.push(aa(item, pagePath));
    });
  }
  return list;
}

function getBtnlists(lists, pagePath, arr = []) {
  lists.forEach((item) => {
    let { path, children } = item;
    if (path == pagePath) {
      arr = children.forEach((item) => arr.push(item));
      return arr;
    }
    if (children && children.length > 0) {
      return getBtnlists(children, pagePath, arr);
    }
  });

  return arr;
}

export default {
  name: 'menu',
  namespaced: true,
  state: {
    menuLists: [], //当前app菜单
    allAuthRoutes: [], //所有授权的路由表
    authBtnlists: [], //获取当前页面的按钮权限
    firstMenuPath: '', //首菜单项路径
    activeMenuPath: '', //当前被激活的菜单
  },
  mutations: {
    // 获取当前app菜单
    saveMenuLists(state, payload) {
      state.menuLists = [...payload];
      let lists = filterRouters(payload, 3);
      lists.push({path:'/'})
      lists.push({path:'/index'})
      // state.allAuthRoutes = filterRouters(payload, 3);
      state.allAuthRoutes = lists;

      state.firstMenuPath = `/${getFirstMenuPath(payload)}`;
    },
    setActiveMenuPath(state, payload) {
      let { path } = payload;
      state.activeMenuPath = path;
    },
    getAuthBtnlists(state, payload) {
      let { path } = payload;
      state.authBtnlists = getBtnlists(state.menuLists, path.split('/')[1]).map((item) => item.path);
    },
  },
};
